--[[

**************************************************************************
AutoTabard
by evil.oz

v1.61
-----
added battleground raid check, should no more spam in bg group

v1.6
----
added exhalted check, fixed bars 4 and 5 colors

v1.5
----
added non heroic lvl 80 dungeons
replaced ENTERING_WORLD with ZONE_CHANGED_NEW_AREA, check will occour more times, but more reliable

v1.4
----
fixed proper action when usual tabard is none

v1.3
----
restyle of the graphic frame

v1.2
----
bugfix when saved tabard status is lost during a ghost-run after dead in instance

v1.1
----
after exit from heroic, previous tabard is restored
bugfix for error msg when entering heroic with no tabard

v1.0
----
initial release




**************************************************************************

]]--


--locale 
if (GetLocale() == "zhCN") then
	AutoTabard_RepFactions={"银色北伐军","黑锋骑士团", "龙眠联军", "肯瑞托", "联盟先遣军"}
	AutoTabard_RepFactionsTabards={"银色北伐军战袍","黑锋骑士团战袍", "龙眠联军战袍", "肯瑞托战袍"}
	AutoTabard_ValidNonHeroics={"闪电大厅", "魔环", "净化斯坦索姆", "乌特加德之巅"}
	FACTION_NOT_FOUND = "阵营未找到"
	not_found = "未找到 (0/0)"
elseif (GetLocale() == "zhTW") then
	AutoTabard_RepFactions={"銀白十字軍","黯刃騎士團", "龍眠協調者", "祈倫托", "聯盟先鋒"}
	AutoTabard_RepFactionsTabards={"銀白十字軍外袍","黯刃外袍", "龍眠協調者外袍", "祈倫托外袍"}
	AutoTabard_ValidNonHeroics={"雷光大廳", "奧核之眼", "斯坦索姆的抉擇", "俄特加德之巔"}
	FACTION_NOT_FOUND = "陣營未找到"
	not_found = "未找到 (0/0)"
else
	AutoTabard_RepFactions={"Argent Crusade","Knights of the Ebon Blade", "The Wyrmrest Accord", "Kirin Tor", "Alliance Vanguard"}
	AutoTabard_RepFactionsTabards={"Tabard of the Argent Crusade","Tabard of the Ebon Blade", "Tabard of the Wyrmrest Accord", "Tabard of the Kirin Tor"}
	AutoTabard_ValidNonHeroics={"Halls of Lightning", "The Oculus", "The Culling of Stratholme", "Utgarde Pinnacle"}
	FACTION_NOT_FOUND = "FACTION NOT FOUND"
	not_found = "not found (0/0)"
end

-- locale print
local L = {}
if (GetLocale() == "zhCN") then
L = {
	["Entering lvl80 5man instance"] = "进入 Lv80 5人副本",
	["Removing current tabard (had no tabard before instance)"] = "脱下当前战袍（副本前不装备战袍）",
	["Re-equiping "] = "重新装备 ",
	["Faction "] = "阵营 ",
	[" is already fully exhalted. Use /at to change to new one or disable addon"] = " 已达到崇拜。键入 /at 更换新公会徽章或关闭插件",
	[" not found!"] = " 未找到！",
	["Equipping "] = "装备 ",
	[" no space to unequip tabard"] = " 没有空间卸下公会徽章",
	["Now configured for Alliance Vanguard. Addon disabled"] = "现在设置为<联盟先遣军>。插件关闭",
	["Now configured for <"] = "现在设置为 <",
	["|CFFFF0000WARNING! "] = "|CFFFF0000注意! ",
	[" not found in inventory!"] = " 未在背包内找到！",
	[" (no action)"] = " (无动作)"
}
elseif (GetLocale() == "zhTW") then
L = {
	["Entering lvl80 5man instance"] = "進入 Lv80 5人副本",
	["Removing current tabard (had no tabard before instance)"] = "脫下當前戰袍（副本前不裝備戰袍）",
	["Re-equiping "] = "重新裝備 ",
	["Faction "] = "陣營 ",
	[" is already fully exhalted. Use /at to change to new one or disable addon"] = " 已達到崇拜。鍵入 /at 更換新公會徽章或關閉插件",
	[" not found!"] = " 未找到！",
	["Equipping "] = "裝備 ",
	[" no space to unequip tabard"] = " 沒有空間卸下公會徽章",
	["Now configured for Alliance Vanguard. Addon disabled"] = "現在設置為<聯盟先鋒>。插件關閉",
	["Now configured for <"] = "現在設置為 <",
	["|CFFFF0000WARNING! "] = "|CFFFF0000注意! ",
	[" not found in inventory!"] = " 未在背包內找到！",
	[" (no action)"] = " (無動作)"
}
else
L = {
	["Entering lvl80 5man instance"] = "Entering lvl80 5man instance",
	["Removing current tabard (had no tabard before instance)"] = "Removing current tabard (had no tabard before instance)",
	["Re-equiping "] = "Re-equiping ",
	["Faction "] = "Faction ",
	[" is already fully exhalted. Use /at to change to new one or disable addon"] = " is already fully exhalted. Use /at to change to new one or disable addon",
	[" not found!"] = " not found!",
	["Equipping "] = "Equipping ",
	[" no space to unequip tabard"] = " no space to unequip tabard",
	["Now configured for Alliance Vanguard. Addon disabled"] = "Now configured for Alliance Vanguard. Addon disabled",
	["Now configured for <"] = "Now configured for <",
	["|CFFFF0000WARNING! "] = "|CFFFF0000WARNING! ",
	[" not found in inventory!"] = " not found in inventory!",
	[" (no action)"] = " (no action)"
}
end

-- #########################################################################################################
-- onload handler
-- #########################################################################################################
function AutoTabard_OnLoad()


	this:RegisterEvent("UPDATE_FACTION");
	--this:RegisterEvent("PLAYER_ENTERING_WORLD");
	this:RegisterEvent("PLAYER_REGEN_ENABLED");
	this:RegisterEvent("PLAYER_UNGHOST");
	this:RegisterEvent("ZONE_CHANGED_NEW_AREA");


	-- add the slash commands
	SlashCmdList["AUTOTABARD"] = function(msg)
		AutoTabard_cmd(msg);
	end
	SLASH_AUTOTABARD1 = "/at";
	SLASH_AUTOTABARD2 = "/autotabard";

end

function AutoTabard_OnEvent(event)


	if event=="UPDATE_FACTION" then
		if AutoTabard_Frame:IsVisible() then
			AutoTabard_RedrawWindow()
		end
	end

	if (event=="PLAYER_UNGHOST") or (event == "ZONE_CHANGED_NEW_AREA") then

		local inInstance, instanceType = IsInInstance()
		-- instanceType: "none" "pvp" "arena" "party" "raid"

		AutoTabard_inInstance = inInstance and (instanceType  == "party") and (AutoTabard_IsRepInstance())
		
		if UnitIsGhost("player") ~= 1 then
			if AutoTabard_inInstance then
				AutoTabard_Print(L["Entering lvl80 5man instance"]);
				AutoTabard_CheckTabard()
			else
				if AutoTabard_SavedTabard then
					-- there is a saved status , created upon autoequip of tabard
					if (AutoTabard_SavedTabard=="EMPTY SLOT") then
						AutoTabard_Print(L["Removing current tabard (had no tabard before instance)"]);
						AutoTabard_RemoveTabard()
						AutoTabard_SavedTabard=nil
					else
						AutoTabard_Print(L["Re-equiping "]..AutoTabard_SavedTabard);
						EquipItemByName(AutoTabard_SavedTabard) 
						AutoTabard_SavedTabard=nil
					end
				end
			end
		end
	end

	if (event == "PLAYER_REGEN_ENABLED") then
		if AutoTabard_inInstance then
			AutoTabard_CheckTabard()	
		end
	end

end

function AutoTabard_IsRepInstance()

	if (GetCurrentDungeonDifficulty() == 2)  then
		--heroic
		return true
	else
		local n, value
		local z=GetRealZoneText()

		value=false
		for n=1, table.getn(AutoTabard_ValidNonHeroics) do
			if (AutoTabard_ValidNonHeroics[n]==z) then
				value=true
				break
			end
		end
		return value
	end
end


function AutoTabard_CheckTabard()

	local itemname	
	local equippedTabard=GetInventoryItemLink("player",GetInventorySlotInfo("TabardSlot"))
	
	if equippedTabard then
		itemName = GetItemInfo(equippedTabard) 
	else
		itemName = "EMPTY SLOT"
	end

	local n

	if AutoTabard_DesiredFaction then
		for n=1,4 do
			if (AutoTabard_DesiredFaction==AutoTabard_RepFactions[n]) then
				-- n is the name of the FACTION selected for farming

				--check if exhalted

				local factionIndex
				local isExhalted=false

				for factionIndex = 1, GetNumFactions() do
					local name, _, _, _, _, earnedValue = GetFactionInfo(factionIndex)						
					if ( name==AutoTabard_DesiredFaction ) and ( earnedValue==42999 ) then
						AutoTabard_Print(L["Faction "]..name..L[" is already fully exhalted. Use /at to change to new one or disable addon"])
						isExhalted=true
						break
					end
				end


				if (itemName==AutoTabard_RepFactionsTabards[n]) then
					--equipped tabard is the one we need

				else
					--equipped tabard is NOT the one we need
					--equip only if not yet exhalted 
					if not isExhalted then
						if GetItemCount(AutoTabard_RepFactionsTabards[n])==0 then
							AutoTabard_Print(""..AutoTabard_RepFactionsTabards[n]..L[" not found!"])
						else
							AutoTabard_Print(L["Equipping "]..AutoTabard_RepFactionsTabards[n])
							EquipItemByName(AutoTabard_RepFactionsTabards[n]) 
							AutoTabard_SavedTabard=itemName
						end
					end
				end
				break
			end
		end

	end

end




function AutoTabard_RemoveTabard()

	-- slots=GetContainerNumFreeSlots(n)
	-- where n is
	-- 0 - Backpack
	-- 1 - Bag 1
	-- 2 - Bag 2
	-- 3 - Bag 3
	-- 4 - Bag 4


	local n
	local found=false

	for n=4,0,-1 do

		if not found then
			local slots=GetContainerNumFreeSlots(n) 

			--AutoTabard_Print("bag "..n..": "..slots.." free slots")
			if slots >0 then
	
				ClearCursor()
				local slotId= GetInventorySlotInfo("TabardSlot")
				PickupInventoryItem(slotId) 
	
				if n==0 then
					--AutoTabard_Print("bag "..n..": storing in backpack")
					PutItemInBackpack()
				else
					--AutoTabard_Print("bag "..n..": storing in slot "..19+n)
					PutItemInBag(19+n) 
				end
				found=true
			end
		end
	end

	if not found then
		AutoTabard_Print(L[" no space to unequip tabard"])
	end

end

function AutoTabard_Click(b1, b2)

	local ButtonNumber=tonumber(string.sub(b1:GetName(), -1))

	if ButtonNumber==5 then
		AutoTabard_DesiredFaction=nil
		AutoTabard_Print(L["Now configured for Alliance Vanguard. Addon disabled"])
	else
		AutoTabard_DesiredFaction=AutoTabard_RepFactions[ButtonNumber]
		AutoTabard_Print(L["Now configured for <"]..AutoTabard_DesiredFaction..">")
		if GetItemCount(AutoTabard_RepFactionsTabards[ButtonNumber])==0 then
			AutoTabard_Print(L["|CFFFF0000WARNING! "]..AutoTabard_RepFactionsTabards[ButtonNumber]..L[" not found in inventory!"])
		end
	end
	
	AutoTabard_RedrawWindow()
end


function AutoTabard_cmd(msg)

	if AutoTabard_Frame:IsVisible() then
		AutoTabard_Frame:Hide()
		--AutoTabard_Print("Frame is now hidden")
	else
		AutoTabard_Frame:Show()
		AutoTabard_RedrawWindow()
		--AutoTabard_Print("Frame is now hisible")
	end
end



function AutoTabard_RedrawWindow()

	local factionIndex, rep

	for factionIndex = 1, GetNumFactions() do
		
		local name, _, _, _, _, earnedValue = GetFactionInfo(factionIndex)
		local text, rep, max, verboseName, color = AutoTabard_ConvertRep(earnedValue)

		if (name==AutoTabard_RepFactions[1]) then
			AutoTabard_Frame1Label:SetText("|CFFFFFFFF"..name)
			AutoTabard_Frame1BarLabel:SetText(text)
			AutoTabard_Frame1BarTexture:SetWidth(186*(rep/max))
			AutoTabard_Frame1BarTexture:SetTexture(AutoTabard_HexToRGB(color))
		end
		if (name==AutoTabard_RepFactions[2]) then
			AutoTabard_Frame2Label:SetText("|CFFFFFFFF"..name)
			AutoTabard_Frame2BarLabel:SetText(text)
			AutoTabard_Frame2BarTexture:SetWidth(186*(rep/max))
			AutoTabard_Frame2BarTexture:SetTexture(AutoTabard_HexToRGB(color))
		end
		if (name==AutoTabard_RepFactions[3]) then
			AutoTabard_Frame3Label:SetText("|CFFFFFFFF"..name)
			AutoTabard_Frame3BarLabel:SetText(text)
			AutoTabard_Frame3BarTexture:SetWidth(186*(rep/max))
			AutoTabard_Frame3BarTexture:SetTexture(AutoTabard_HexToRGB(color))
		end
		if (name==AutoTabard_RepFactions[4]) then
			AutoTabard_Frame4Label:SetText("|CFFFFFFFF"..name)
			AutoTabard_Frame4BarLabel:SetText(text)
			AutoTabard_Frame4BarTexture:SetWidth(186*(rep/max))
			AutoTabard_Frame4BarTexture:SetTexture(AutoTabard_HexToRGB(color))
		end
		if (name==AutoTabard_RepFactions[5]) then
			AutoTabard_Frame5Label:SetText("|CFFFFFFFF"..name..L[" (no action)"])
			AutoTabard_Frame5BarLabel:SetText(text)
			AutoTabard_Frame5BarTexture:SetWidth(186*(rep/max))
			AutoTabard_Frame5BarTexture:SetTexture(AutoTabard_HexToRGB(color))
		end
	end

	for factionIndex=1,4 do

		local control=getglobal("AutoTabard_Frame"..factionIndex)
		local background=getglobal("AutoTabard_Frame"..factionIndex.."Color")

		if (AutoTabard_DesiredFaction) and (AutoTabard_RepFactions[factionIndex]==AutoTabard_DesiredFaction) then
			background:SetTexture(0.1,0.1,0.1,1)
			control:SetBackdropBorderColor(1,1,1,1)
			control:SetAlpha(1)
		else 
			background:SetTexture(0,0,0,1)
			control:SetBackdropBorderColor(0.8,0.8,0.8,0.5)
			control:SetAlpha(0.4)
		end
			
	end

	local control=getglobal("AutoTabard_Frame5")
	local background=getglobal("AutoTabard_Frame5Color")

	if (not AutoTabard_DesiredFaction) then
		background:SetTexture(0.1,0.1,0.1,1)
		control:SetBackdropBorderColor(1,1,1,1)
		control:SetAlpha(1)
	else 
		background:SetTexture(0,0,0,0)
		control:SetBackdropBorderColor(0.8,0.8,0.8,0.5)
		control:SetAlpha(0.4)
	end


end

function AutoTabard_ConvertRep(value)

	local text, rep, max, verboseName, color

	rep=0
	max=0
	verboseName="none"

	
	if (value>1) and (value<3000) then 
		rep=value
		max=3000
		verboseName="Neutral"
		color="A68818"
	end
	if (value>2999) and (value<9000) then 
		rep=value-3000
		max=6000
		verboseName="Friendly"
		color="777601"
	end
	if (value>8999) and (value<21000) then 
		rep=value-9000
		max=12000
		verboseName="Honored"
		color="567601"
	end
	if (value>20999) and (value<42000) then 
		rep=value-21000
		max=21000
		verboseName="Revered"
		color="237801"
	end
	if (value>41999) then 
		rep=value-42000
		max=1000
		verboseName="Exhalted"
		color="007662"
	end

	text="|cFFFFFFFF"..verboseName.." ("..rep.."/"..max..")" 

	

	return text, rep, max, verboseName, color

end

function AutoTabard_HexToRGB(hex)
	local rhex, ghex, bhex = string.sub(hex, 1, 2), string.sub(hex, 3, 4), string.sub(hex, 5, 6)
	return tonumber(rhex, 16)/255, tonumber(ghex, 16)/255, tonumber(bhex, 16)/255
end



-- #########################################################################################################
-- misc service functions
-- #########################################################################################################
function AutoTabard_Print(str)

	if str then
		str="[AutoTabard] |CFFFFFFFF"..str
	end

	DEFAULT_CHAT_FRAME:AddMessage(str, 1.0, 1.0, 0.0);

end



function AutoTabard_Message(msg)
	UIErrorsFrame:AddMessage(msg, 1.0, 0, 0, 1.0, 1);
end